const { User, City, UserCity } = require('../models');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const { generateToken } = require('../services/authService');
const { Op } = require('sequelize');

// 注册
const register = async (req, res) => {
  try {
    const { username, email, password } = req.body;

    const existingUser = await User.findOne({ where: { email } });
    if (existingUser) {
      return res.status(400).json({ error: '用户已存在' });
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    const user = await User.create({ username, email, password: hashedPassword });

    res.status(201).json({ message: '注册成功', user: { user_id: user.user_id, username: user.username, email: user.email } });
  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({ error: '注册失败', details: error.message });
  }
};

// 登录
const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    console.log(`Login attempt for email: ${email}`);

    const user = await User.findOne({ where: { email } });
    if (!user) {
      return res.status(400).json({ error: '用户不存在' });
    }

    console.log(`User found: ${user.username}`);
    const isValidPassword = await bcrypt.compare(password, user.password);
    console.log(`Password comparison result (isValidPassword): ${isValidPassword}`);

    if (!isValidPassword) {
      return res.status(400).json({ error: '密码错误' });
    }

    const token = generateToken(user.user_id);
    res.json({ message: '登录成功', token });
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({ error: '登录失败', details: error.message });
  }
};

// 用户设置默认城市
const setDefaultCity = async (req, res) => {
  const { cityId } = req.body;
  const userId = req.user.user_id; // 从 token 中获取用户ID

  if (!cityId) {
    return res.status(400).json({ error: '请提供城市ID' });
  }

  try {
    // 查找用户是否已经有该城市的关联
    let userCity = await UserCity.findOne({
      where: { user_id: userId, city_id: cityId }
    });

    if (userCity) {
      // 如果已经存在，更新其为默认
      await userCity.update({ is_default: true });
    } else {
      // 如果不存在，创建新的关联并设置为默认
      userCity = await UserCity.create({
        user_id: userId,
        city_id: cityId,
        is_default: true
      });
    }

    // 将用户其他城市的 is_default 设置为 false
    await UserCity.update(
      { is_default: false },
      {
        where: {
          user_id: userId,
          city_id: { [Op.ne]: cityId }
        }
      }
    );

    res.status(200).json({ message: '默认城市设置成功' });
  } catch (error) {
    console.error('设置默认城市失败:', error);
    res.status(500).json({ error: '设置默认城市失败', details: error.message });
  }
};

// 获取用户信息
const getUserInfo = async (req, res) => {
  try {
    const userId = req.user.user_id; // 从 JWT token 中获取用户 ID
    console.log(`getUserInfo: Received request for userId: ${userId}`);
    const user = await User.findByPk(userId, {
      attributes: ['user_id', 'username', 'email', 'avatar_url'],
      include: [{
        model: City,
        through: { model: UserCity, where: { is_default: true } },
        required: false // 使用 left join，即使没有默认城市也不会报错
      }]
    });
    console.log('getUserInfo: User found:', user ? user.username : 'None');

    if (!user) {
      return res.status(404).json({ error: '用户未找到' });
    }

    const defaultCity = user.Cities && user.Cities.length > 0 ? user.Cities[0] : null;
    console.log('getUserInfo: Default city found:', defaultCity ? defaultCity.name : 'None');

    res.json({
      user_id: user.user_id,
      username: user.username,
      email: user.email,
      avatar_url: user.avatar_url,
      defaultCity: defaultCity ? { city_id: defaultCity.city_id, name: defaultCity.name } : null
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ error: '获取用户信息失败', details: error.message });
  }
};

// 添加收藏城市
const addFavoriteCity = async (req, res) => {
  const { cityId } = req.body;
  const userId = req.user.user_id;

  if (!cityId) {
    return res.status(400).json({ error: '请提供城市ID' });
  }

  try {
    const city = await City.findByPk(cityId);
    if (!city) {
      return res.status(404).json({ error: '城市不存在' });
    }

    const existingFavorite = await UserCity.findOne({
      where: { user_id: userId, city_id: cityId }
    });

    if (existingFavorite) {
      return res.status(409).json({ message: '该城市已在您的收藏中' });
    }

    await UserCity.create({
      user_id: userId,
      city_id: cityId,
      is_default: false // 收藏的城市不是默认城市
    });

    res.status(201).json({ message: '城市已成功添加到收藏' });
  } catch (error) {
    console.error('添加收藏城市失败:', error);
    res.status(500).json({ error: '添加收藏城市失败', details: error.message });
  }
};

// 获取收藏城市列表
const getFavoriteCities = async (req, res) => {
  const userId = req.user.user_id;

  try {
    const user = await User.findByPk(userId, {
      include: [{
        model: City,
        through: { model: UserCity }, // 获取所有关联城市，不限是否默认
        attributes: ['city_id', 'name', 'city_code'] // 只选择需要的城市属性
      }],
      attributes: [] // 不需要用户自身属性，只获取关联城市
    });

    if (!user) {
      return res.status(404).json({ error: '用户未找到' });
    }

    // 过滤掉默认城市，如果需要单独显示的话，或者根据 is_default 标记进行前端渲染
    const favoriteCities = user.Cities.map(city => ({
      city_id: city.city_id,
      name: city.name,
      city_code: city.city_code
    }));

    res.status(200).json({ cities: favoriteCities });
  } catch (error) {
    console.error('获取收藏城市失败:', error);
    res.status(500).json({ error: '获取收藏城市失败', details: error.message });
  }
};

// 更新用户资料
const updateUserProfile = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { username } = req.body;

    if (!username) {
      return res.status(400).json({ error: '昵称不能为空' });
    }

    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({ error: '用户未找到' });
    }

    user.username = username;
    await user.save();

    res.status(200).json({ message: '用户资料更新成功', username: user.username });
  } catch (error) {
    console.error('更新用户资料失败:', error);
    res.status(500).json({ error: '更新用户资料失败', details: error.message });
  }
};

// 修改密码
const changePassword = async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { oldPassword, newPassword } = req.body;

    if (!oldPassword || !newPassword) {
      return res.status(400).json({ error: '旧密码和新密码都不能为空' });
    }

    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({ error: '用户未找到' });
    }

    const isValidPassword = await bcrypt.compare(oldPassword, user.password);
    if (!isValidPassword) {
      return res.status(401).json({ error: '旧密码不正确' });
    }

    const hashedNewPassword = await bcrypt.hash(newPassword, 10);
    user.password = hashedNewPassword;
    await user.save();

    res.status(200).json({ message: '密码修改成功' });
  } catch (error) {
    console.error('修改密码失败:', error);
    res.status(500).json({ error: '修改密码失败', details: error.message });
  }
};

// 上传头像
const uploadAvatar = async (req, res) => {
  try {
    console.log('[uploadAvatar] Received upload request.');
    const userId = req.user.user_id;
    console.log(`[uploadAvatar] User ID: ${userId}`);
    const user = await User.findByPk(userId);

    if (!user) {
      console.error('[uploadAvatar] 用户未找到.');
      return res.status(404).json({ error: '用户未找到' });
    }

    if (!req.file) {
      console.error('[uploadAvatar] 没有上传文件。');
      return res.status(400).json({ error: '没有上传文件' });
    }

    console.log('[uploadAvatar] File received:', req.file);
    // 构建头像的相对 URL 路径
    // 假设您的服务器静态文件服务配置为 /uploads，并且头像存储在 /uploads/avatars
    const avatarUrl = `/uploads/avatars/${req.file.filename}`;
    console.log(`[uploadAvatar] Generated avatar URL: ${avatarUrl}`);

    user.avatar_url = avatarUrl;
    await user.save();
    console.log('[uploadAvatar] User avatar_url updated in database.');

    res.status(200).json({ message: '头像上传成功', avatar_url: avatarUrl });
  } catch (error) {
    console.error('上传头像失败:', error);
    res.status(500).json({ error: '上传头像失败', details: error.message });
  }
};

module.exports = {
  register,
  login,
  getUserInfo,
  setDefaultCity,
  addFavoriteCity,
  getFavoriteCities,
  updateUserProfile,
  changePassword,
  uploadAvatar,
};